<template>
  <div class="SPKManage">
    <div>
      <h4>商品库存管理</h4>
    </div>
    <el-form>
      <el-form-item label="商品:">
        <el-col :span="12">
          <div class="card-list">
            <el-card :body-style="{ padding: '0' }" shadow="never">
              <div class="ele-content">
                <div class="left commodity">
                  <!--                  <img
                    :src="$route.params.row ? $route.params.row.picUrl : ''"
                    alt=""
                  >-->
                  <TableColumnGoodsImage :src="goodsInfo.picUrl" :img-size="'60px'" />
                </div>
                <div class="commodity">
                  <p>
                    {{ goodsInfo.name }}
                  </p>
                  <p>
                    类型:{{
                      goodsInfo.goodsType == 'sale'? '售卖': '租赁'
                    }}
                  </p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-form-item>
      <el-form-item label="规格:">
        <el-col :span="20">
          <div class="Specifications">
            <div class="cations-tag">
              <el-row v-for="(item, index) in list" :key="index">
                <SpecItem
                  ref="SpecItem"
                  :index="index"
                  :type="3"
                  :table-head="item"
                />
              </el-row>
            </div>
            <!--            <div v-for="(item, index) in list" :key="index" class="cations-tag">
              <div class="top">
                <span>规格名:</span><el-input v-model="item.name" disabled />
              </div>
              <div
                v-for="(vake, indx) in item.valueList"
                :key="indx"
                class="bottom"
              >
                <span>规格值:</span><el-input v-model="vake.value" disabled />
              </div>
            </div>-->
          </div>
          <table v-show="list && list.length > 0" class="ele-spec-table">
            <thead>
              <tr v-if="theadList && theadList.length > 0">
                <td v-for="(item, index) in theadList" :key="index">
                  {{ item }}
                </td>
              </tr>
            </thead>
            <tbody>
              <!--              <tr v-for="(item, index) in tbodyList" :key="index">
                <td
                  v-for="(i, j) in item"
                  v-show="i.val !== ''"
                  :key="j"
                  :rowspan="i.rowspan"
                >
                  <span
                    v-show="
                        i.val !== 'stock'
                    "
                  >{{ i.val }}</span>
                  <el-input
                    v-if="i.val === 'stock'"
                    v-model="i.warehouseCount"
                    placeholder="请输入库存"
                  />
                </td>
              </tr>-->
              <tr v-for="(item,index) in tbodyList" :key="index">
                <td v-for="(i,j) in item" v-show="i.val!==''" :key="j" :rowspan="i.rowspan">
                  <span v-show="i.val!=='stock'">{{ i.val }}</span>
                  <goods-stock-value v-if="i.val==='stock'" ref="GoodsStockValue" :change-stock-disabled="changeStockDisable" :index="j" :commodity-id="regularProductId[index]" :table-price="regularStockValue[index]" />
                </td>
              </tr>
            </tbody>
          </table>
        </el-col>
      </el-form-item>

      <el-form-item class="ele-footer">
        <el-button type="primary" @click="handelSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import SpecItem from '@/components/SpecItem'
/** 商品库存管理 */
import {
  EditWarehouse,
  modifyMessage
} from '@/api/customAPI/shop/GloudWarehouse'
import TableColumnGoodsImage from '@/components/TableColumnGoodsImage'
import GoodsStockValue from '@/components/GoodsStockValue'
export default {
  name: 'SPKManage',
  components: {
    SpecItem,
    TableColumnGoodsImage,
    GoodsStockValue
  },
  data() {
    return {
      goodsInfo: {
        goodsId: '',
        picUrl: '',
        name: '',
        goodsType: ''
      },
      cloudId: '',
      bindData: [],
      regualrList: [],
      column: [],
      tableList: [],
      theadList: [],
      tbodyList: [],
      list: [],
      goodsSpecList: [],
      regularStockValue: [],
      regularProductId: [],

      extraList: [],
      extraTable: [],
      extraGoods: [],

      commoditySale: {},
      /* deposit: {
        name: '押金',
        values: [
          {
            val: 'deposit'
          }
        ]
      },*/
      stock: {
        name: '库存',
        values: [
          {
            val: 'stock'
          }
        ]
      },
      disabled: false,
      stockDisabled: false
    }
  },
  created() {
    this.init()
  },
  mounted() {
    this.init()
  },
  activated() {
    this.init()
  },
  methods: {
    /** 提交 */
    handelSubmit() {
      console.log(this.tbodyList, 'tbodyList')
      const params = []
      this.$nextTick(() => {
        this.$refs.GoodsStockValue.forEach(item => {
          params.push({
            id: item.commodityId,
            warehouseCount: item.getData()
          })
        }
        )
        EditWarehouse({
          commodityID: this.goodsInfo.goodsId,
          warehouseId: this.cloudId,
          specifications: params
        }).then(result => {
          this.$message.success('成功')
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.go(-1)
        })
      })
      /* for (let i = 0; i < this.tbodyList.length; i++) {
        for (let j = 0; j < this.tbodyList[i].length; j++) {
          if (
            this.tbodyList[i][j].specId &&
            this.tbodyList[i][j].warehouseCount
          ) {
            params.push({
              id: this.tbodyList[i][j].specId,
              warehouseCount: this.tbodyList[i][j].warehouseCount
            })
          }
        }
      }*/
    },
    // 初始规格
    init() {
      const param = this.$dd(this.$route.query.p)
      this.goodsInfo.goodsId = param.row.goodsId
      this.goodsInfo.name = param.row.goodsName
      this.goodsInfo.picUrl = param.row.picUrl
      this.goodsInfo.goodsType = param.row.goodsType
      this.cloudId = param.row.cloudId
      modifyMessage({
        goodsId: param.row.goodsId || '',
        cloudId: param.row.cloudId || ''
      }).then(response => {
        console.log(response.data.data)
        response.data.data.regualrCombo.forEach(inf => {
          this.regularProductId.push(inf.productId)
          this.regularStockValue.push(inf.cloudStock)
          /* inf.regualrs.forEach(reg => {
            response.data.data.regualrList.forEach(list => {
              list.valueList.forEach(lit => {
                if (reg.specId === lit.specId) {
                  lit.cloudStock = inf.cloudStock
                  this.stock.values.push({
                    specId: lit.specId,
                    productId: inf.productId,
                    cloudStock: inf.cloudStock,
                    val: 'stock'
                  })
                }
              })
            })
          })*/
        })
        this.loadGoodsSpec(response.data.data.regualrList)
      })
    },

    changeDisable() {
      this.disabled = true
    },
    changeStockDisable() {
      this.stockDisabled = true
    },
    /** 常规规格加载方法*/
    loadGoodsSpec(a) {
      this.list = []
      a.forEach(item => {
        this.list.push(item)
      })
      this.$nextTick(() => {
        for (let i = 0; i < this.list.length; i++) {
          this.$refs.SpecItem[i].$data.tableHead.name = this.list[i].name
          this.$refs.SpecItem[i].$data.tableHead.values = this.list[i].valueList
          for (let j = 0; j < this.list[i].valueList.length; j++) {
            this.$refs.SpecItem[i].$data.tableHead.values[j].val = this.list[i].valueList[j].value
          }
        }
        this.createTable()
      })
    },
    // 创建表格
    createTable() {
      this.tableList = []
      if (this.list && this.list.length !== 0) {
        this.$refs.SpecItem.forEach(item => {
          this.tableList.push(item.getData())
          console.log(item)
        })
      }
      const arrList = []
      const headList = []
      this.tableList.push(this.stock)
      console.log(this.tableList)
      this.tableList.forEach(item => {
        if (item.name) {
          headList.push(item.name)
          if (item.values && item.values.length !== 0) {
            arrList.push(item.values)
          }
        }
      })
      this.theadList = headList
      console.log(arrList)
      const modelList = this.cartesianProductOf(...arrList)
      console.log(modelList)
      const list = []
      const count = 1

      for (let i = 0; i < modelList.length; i++) {
        const modelArrList = []
        for (let k = 0; k < modelList[i].length; k++) {
          modelArrList.push({
            val: modelList[i][k].val,
            commodityId: '',
            index: k,
            rowspan: count
          })
        }
        list.push(modelArrList)
      }
      console.log(list)
      this.tableRowspan(list, modelList)

      this.tbodyList = list
      console.log(list)
    },
    /* createTable() {
      this.tableList = []
      if (this.list && this.list.length !== 0) {
        this.$refs.SpecItem.forEach(item => {
          this.tableList.push(item.getData())
        })
      }
      var arrList = []
      const headList = []

      this.tableList.push(this.stock)

      this.tableList.forEach(item => {
        if (item.name) {
          headList.push(item.name)
          if (item.values && item.values.length !== 0) {
            arrList.push(item.values)
          }
        }
      })
      this.theadList = headList
      const modelList = this.cartesianProductOf(...arrList)
      const list = []
      const count = 1

      for (let i = 0; i < modelList.length; i++) {
        var modelArrList = []
        for (let k = 0; k < modelList[i].length; k++) {
          modelArrList.push({
            val: modelList[i][k].val,
            index: k,
            rowspan: count,
            warehouseCount: modelList[i][k].cloudStock,
            specId: modelList[i][k].specId,
            productId:modelList[i][k].productId
          })
        }
        list.push(modelArrList)
      }
      // list.splice(list.length - 1, 1)
      this.tableRowspan(list, modelList)

      this.tbodyList = list
      console.log(this.tableList)
    },*/
    // table合并行方法 a为table数组 b为对比数组
    tableRowspan(a, b) {
      for (let i = 0; i < a.length - 1; i++) {
        for (let k = 0; k < a[i].length; k++) {
          for (let j = i + 1; j < b.length; j++) {
            if (k === 0) {
              if (a[i][k].val === b[j][k].val) {
                a[i][k].rowspan++
                a[j][k].val = ''
              } else {
                console.log({ i, j, k })
                break
              }
            } else {
              if (a[i][k].val === b[j][k].val && a[j][k - 1].val === '') {
                a[i][k].rowspan++
                a[j][k].val = ''
              } else {
                console.log({ i, j, k })
                break
              }
            }
          }
        }
      }
    },
    // 笛卡尔积
    cartesianProductOf() {
      return Array.prototype.reduce.call(
        arguments,
        function(a, b) {
          const ret = []
          a.forEach(function(a) {
            b.forEach(function(b) {
              ret.push(a.concat([b]))
            })
          })
          return ret
        },
        [[]]
      )
    }
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch('tagsView/delView', from)
    next()
  }
}
</script>

<style lang="scss" scoped>
.SPKManage {
  padding: 50px 100px;
  ::v-deep.el-form {
    .el-form-item__label {
      width: 60px;
      text-align: start;
    }
    .ele-footer {
      margin-left: 60px;
      .el-button {
        width: 100px;
      }
    }
  }
  .el-form-item {
    .card-list {
      width: 100%;
      display: flex;
      align-items: flex-start;
      flex-wrap: wrap;
      ::v-deep.el-card {
        padding: 10px;
        .el-card__header {
          border: none;
          padding: 0;
        }
        min-width: 350px;
        .ele-content {
          display: flex;
          align-items: center;
          .left {
            margin-left: 20px;
            width: 60px;
            height: 60px;
            img {
              width: 100%;
              height: 100%;
              image-rendering: -moz-crisp-edges;
              image-rendering: -o-crisp-edges;
              image-rendering: crisp-edges;
              -ms-interpolation-mode: nearest-neighbor;
            }
          }
          .commodity {
            margin-left: 20px;
            font-size: 16px;
            p {
              margin: 0;
            }
          }
          .right {
            margin-left: 10px;
            p {
              margin: 0;
              padding: 0;
            }
            p:first-child {
              font-weight: bold;
              font-size: 20px;
            }
            p:last-child {
              color: gray;
              font-size: 14px;
            }
          }
        }
      }
      ::v-deep.el-button {
        margin-left: 2%;
      }
    }

    .Specifications {
      padding: 40px 20px;
      width: 100%;
      border: 1px solid #e6e6e6;
      .cations-tag {
        ::v-deep.el-row {
          margin-top: 15px;
        }
        .ele-col-item {
          width: 60px;
        }
        .top,
        .bottom {
          display: flex;
          align-items: center;
          span {
            display: inline-block;
            min-width: 100px;
          }
          .el-input {
            width: 200px;
            margin: 5px 0px;
          }
        }
      }
    }
    .ele-table {
      width: 100%;
      margin-top: 40px;
      .ele-div-footer {
        display: flex;
        justify-content: space-between;
        margin: 50px 0px 100px 0px;
        .footer-left {
          ::v-deep.el-button {
            width: 100px;
            margin: 0px;
          }
        }
      }
    }
    .ele-spec-table {
      min-width: 100%;
      border-collapse: collapse;
      margin-top: 30px;
      tr td {
        width: 80px;
        border: 1px solid #e6e6e6;
        box-sizing: border-box;
        text-align: center;
      }
      thead {
        font-weight: bold;
        tr td {
          height: 60px;
        }
      }
      tbody {
        tr {
          td {
            ::v-deep.el-image {
              width: 50px;
              height: 50px;
              object-fit: cover;
              border: 1px solid #e6e6e6;
              overflow: unset;
              margin: 10px 0px;
            }
            ::v-deep.el-input {
              width: 120px;
            }
            .custom {
              display: flex;
              align-items: center;
              justify-content: center;
              span {
                margin-left: 5px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
